<?php

ini_set('memory_limit', '1024M');

use Fukuball\Jieba\Jieba;
use Fukuball\Jieba\Finalseg;
use Fukuball\Jieba\JiebaAnalyse;
use function GuzzleHttp\json_encode;
use function GuzzleHttp\json_decode;

Jieba::init();
Finalseg::init();
JiebaAnalyse::init();

// 政策库模型
class zhengcekuModule extends Model
{
    public function __construct()
    {
        parent::__construct("zhengceku");
    }

    /**
     * 查询政策列表
     * @date: 2019年6月13日 上午11:46:11
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getzhengcekuList($startSet = 0, $endSet = 10, $orderBy = "", $whereStr = "status = 1")
    {
        if ($orderBy == "") {
            $orderBy = " fawenriqi desc,id desc";
        } else {
            $orderBy = $orderBy . " ,fawenriqi desc,id desc";
        }
        if ($whereStr == "") {
            $whereStr = " chaifenzhuangtai = 3 ";
        } else {
            $whereStr = $whereStr . " and chaifenzhuangtai = 3 ";
        }
        //自定义查询条件
        $sousuorizhiM = new model("sousuorizhi");
        $searchdata = $this->getFieldArray();
        foreach ($searchdata as $k => $v) {
            if ($v != "") {
                if ($k == "fawenriqi") {
                    $temp_date = explode('|', $v); //$hello = explode(',',$source);
                    $date_start = trim($temp_date[0]);
                    $date_end = trim($temp_date[1]);

                    $whereStr = $whereStr . " and fawenriqi between '{$date_start}' and '{$date_end}' ";
                } else if ($k == "jibie") {
                    $whereStr = $whereStr . " and {$k} in ({$v}) ";

                } else {
                    $whereStr = $whereStr . " and {$k}='{$v}' ";
                }
                //记录搜索日志 start
                if ($k == "fuchifangxiang") {
                    $sousuorizhi_data["dtime"] = date("Y-m-d H:i:s");
                    $sousuorizhi_data["leixing"] = "扶持方向";
                    $fuchifangxiang_str = (new parameterModel())->find("u1")->where("classid='376' and u2='{$v}' ")->one();
                    if (count($fuchifangxiang_str) > 0) {
                        $sousuorizhi_data["neirong"] = $fuchifangxiang_str["u1"];
                        $sousuorizhiM->insert($sousuorizhi_data);
                    }
                }
            }
        }

        //全表模糊查询
        $search_value = $this->common->Requert("search_value");
        $sql = "";
        if ($search_value != "") {
            $sql = " (biaoti like '%{$search_value}%') ";
            $sql_search = " (content like '%{$search_value}%' or biaoqian like '%{$search_value}%')  ";
            $count_sql = " (biaoti like '%{$search_value}%'or content like '%{$search_value}%' or biaoqian like '%{$search_value}%') ";

            //记录搜索日志 start
            $sousuorizhi_data["dtime"] = date("Y-m-d H:i:s");
            $sousuorizhi_data["leixing"] = "搜索词";
            $sousuorizhi_data["neirong"] = $search_value;
            $sousuorizhiM->insert($sousuorizhi_data);
            //记录搜索日志 end
        }
        $where_search = $whereStr;
        $where_count = $whereStr;
        if ($sql != "") {
            $whereStr = $whereStr . " and " . $sql;
            $where_search = $where_search . " and " . $sql_search;
            $where_count = $where_count . " and " . $count_sql;
        }
        $count = count($this->where($where_count)->all());
        //组装sql查询语句
        $offset = ($startSet - 1) * $endSet;
        $sql_result = "SELECT * FROM(SELECT id,sort_id,biaoti,fawenriqi,biaoqian,renqi,description,content,jiezhiriqi,jibie,hexinneirong FROM sl_zhengceku
                    WHERE {$whereStr} ORDER BY {$orderBy}) a 
                    UNION ALL
                    (SELECT id,sort_id,biaoti,fawenriqi,biaoqian,renqi,description,content,jiezhiriqi,jibie,hexinneirong FROM sl_zhengceku WHERE {$where_search} 
                    ORDER BY {$orderBy}) limit $offset,$endSet";
        //查询数据
        $list = $this->findBySql($sql_result);

//        $list = $this
//            ->find("id,sort_id,biaoti,fawenriqi,biaoqian,renqi,description,content,jiezhiriqi,jibie,hexinneirong")
//            ->where($whereStr)
//            ->orderBy($orderBy)
//            ->limit(($startSet - 1) * $endSet, $endSet)
//            ->all();

        $parameterM = new parameterModel();
        foreach ($list as $k => $v) {

            //设置摘要
            if (empty($v['description'])) {
                $v['description'] = DeleteHtml(htmlspecialchars_decode($v['hexinneirong']));
//                 var_dump($v['description']);
            }

            //处理发文日期
            if ($v['fawenriqi'] != "") {
                $v['fawenriqi'] = date("Y-m-d", strtotime($v['fawenriqi']));
            }

            //处理标签
            $v['biaoqian'] = str_replace("，", ",", $v['biaoqian']);
            $v['biaoqian'] = ($v['biaoqian'] == null || $v['biaoqian'] == "") ? [] : explode(",", $v['biaoqian']);
            $v['biaoqian'] = array_slice(Arrayremove_nullvalue($v['biaoqian']), 0, 4);

            //处理申请状态
            //jiezhiriqi

            if ($v['jiezhiriqi'] == "" || $v['jiezhiriqi'] == null) {
                $v['zhuangtai'] = "";
            } else {
                $zero1 = time();
                $zero2 = strtotime($v['jiezhiriqi']);

                //政策文件
                if ($v["sort_id"] == "6") {
                    if ($zero1 < $zero2) {
                        //echo “zero1早于zero2′;
                        $v['zhuangtai'] = "";
                    } else {

                        $v['zhuangtai'] = "已失效";
                    }
                }

                //资格资质
                if ($v["sort_id"] == "5") {
                    if ($zero1 < $zero2) {
                        //echo “zero1早于zero2′;
                        $v['zhuangtai'] = "申报中";
                    } else {

                        $v['zhuangtai'] = "已截止";
                    }
                }

                //资金扶持
                if ($v["sort_id"] == "4") {
                    if ($zero1 < $zero2) {
                        //echo “zero1早于zero2′;
                        $v['zhuangtai'] = "申报中";
                    } else {

                        $v['zhuangtai'] = "已截止";
                    }
                }


            }

            //自定义标题
            $jibiedata = $parameterM->where("u2='{$v['jibie']}' and classid in (369,373) ")->one();
            if (count($jibiedata) > 0) {
                if ($jibiedata['classid'] == 373) {
                    $v['biaoti'] = "【区】" . $v['biaoti'];
                } else {
                    $v['biaoti'] = "【{$jibiedata["u1"]}】" . $v['biaoti'];
                }

            }

            //设置摘要
            if (trim($v['description']) == "" || $v['description'] == null) {
                $v['description'] = $v['hexinneirong'];
            }

            unset($v['content']);
            $list[$k] = $v;

        }
        $re_list["data"] = $list;
        $re_list["count"] = $count;
        return $re_list;
    }

    /**
     * 查询我的政策库
     * @date: 2019年7月2日 下午4:29:25
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getMyzhengcekuList($startSet = 0, $endSet = 10, $orderBy = "", $whereStr = "")
    {
        $parameterM = new parameterModel();
        $dingyuelanmuM = new dingyuejiluModule();

        if ($orderBy == "") {
            $orderBy = " fawenriqi desc,id desc";
        } else {
            $orderBy = $orderBy . " ,RAND(),fawenriqi desc,id desc";
        }


        if ($whereStr == "") {
            $whereStr = " chaifenzhuangtai=3 ";
        } else {
            $whereStr = $whereStr . " and chaifenzhuangtai=3 ";
        }
        //自定义查询条件
        $searchdata = $this->getFieldArray();
        foreach ($searchdata as $k => $v) {
            if ($v != "") {
                if ($k == "fawenriqi") {
                    $temp_date = explode('|', $v); //$hello = explode(',',$source);
                    $date_start = trim($temp_date[0]);
                    $date_end = trim($temp_date[1]);

                    $whereStr = $whereStr . " and fawenriqi between '{$date_start}' and '{$date_end}' ";
                } else if ($k == "jibie") {
                    $whereStr = $whereStr . " and {$k} in ({$v}) ";

                } else {
                    $whereStr = $whereStr . " and {$k}='{$v}' ";
                }
            }
        }

        //全表模糊查询

        $search_value = $this->common->Requert("search_value");
        $sql = "";
        if ($search_value != "") {
            $sql = " (biaoti like '%{$search_value}%'  or content like '%{$search_value}%') ";
        }
        //查询用户添加的栏目
        $yonghuid = $this->common->Requert("yonghu");
        if ($yonghuid != "") {
            $dingyuelanmuSql = (new yonghuModule())->getdingyuelanmuSqlByYonghuid($yonghudata['id']);
            if ($dingyuelanmuSql != "") {
                $whereStr = $whereStr . " and " . $dingyuelanmuSql;

            }
        }


        //查询用户的搜索记录

        if ($sql != "") {
            $whereStr = $whereStr . " and " . $sql;
        }

        //var_dump($whereStr);die();


        $list = $this->find("id,sort_id,biaoti,fawenriqi,biaoqian,renqi,description,content,jiezhiriqi,jibie,hexinneirong")->where($whereStr)->orderBy($orderBy)->limit(($startSet - 1) * $endSet, $endSet)->all();


        foreach ($list as $k => $v) {
            //设置摘要
            if (empty($v['description'])) {
                $v['description'] = DeleteHtml(htmlspecialchars_decode($v['hexinneirong']));
                //                 var_dump($v['description']);
            }


            //处理发文日期
            if ($v['fawenriqi'] != "") {
                $v['fawenriqi'] = date("Y-m-d", strtotime($v['fawenriqi']));
            }

            //处理标签
            $v['biaoqian'] = str_replace("，", ",", $v['biaoqian']);
            $v['biaoqian'] = ($v['biaoqian'] == null || $v['biaoqian'] == "") ? [] : explode(",", $v['biaoqian']);
            $v['biaoqian'] = array_slice(Arrayremove_nullvalue($v['biaoqian']), 0, 4);


            //处理申请状态
            //jiezhiriqi

            if ($v['jiezhiriqi'] == "" || $v['jiezhiriqi'] == null) {
                $v['zhuangtai'] = "";
            } else {
                $zero1 = time();
                $zero2 = strtotime($v['jiezhiriqi']);
                //政策文件
                if ($v["sort_id"] == "6") {
                    if ($zero1 < $zero2) {
                        //echo “zero1早于zero2′;
                        $v['zhuangtai'] = "";
                    } else {

                        $v['zhuangtai'] = "已失效";
                    }
                }

                //资格资质
                if ($v["sort_id"] == "5") {
                    if ($zero1 < $zero2) {
                        //echo “zero1早于zero2′;
                        $v['zhuangtai'] = "申报中";
                    } else {

                        $v['zhuangtai'] = "已截止";
                    }
                }

                //资金扶持
                if ($v["sort_id"] == "4") {
                    if ($zero1 < $zero2) {
                        //echo “zero1早于zero2′;
                        $v['zhuangtai'] = "申报中";
                    } else {

                        $v['zhuangtai'] = "已截止";
                    }
                }


            }

            //自定义标题
            $jibiedata = $parameterM->where("u2='{$v['jibie']}' and classid in (369,373) ")->one();
            if (count($jibiedata) > 0) {
                if ($jibiedata['classid'] == 373) {
                    $v['biaoti'] = "【区】" . $v['biaoti'];
                } else {
                    $v['biaoti'] = "【{$jibiedata["u1"]}】" . $v['biaoti'];
                }

            }


            unset($v['content']);
            $list[$k] = $v;

        }
        //var_dump($_list);die();
        $re_list["data"] = $list;
        $re_list["count"] = count($this->where($whereStr)->all());
        return $re_list;

    }

    /**
     * 获取热搜词组
     * @date: 2019年6月13日 下午3:11:57
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getHotWords($number = 3)
    {
        $list = $this->find("biaoqian")->where("biaoqian<>'' and biaoqian is not null ")->orderBy("renqi desc")->all();
        $words = "";
        foreach ($list as $k => $v) {
            if ($words == "") {
                $words = $v['biaoqian'];
            } else {
                $words = $words . "," . $v['biaoqian'];
            }
        }

        $wordsArray = $words == "" ? [] : explode(",", $words);
        $wordsArray = array_unique($wordsArray);
        $temp_wordsArray = [];
        foreach (array_rand($wordsArray, $number) as $k => $v) {
            $temp_wordsArray[] = $wordsArray[$v];
        }
        return $temp_wordsArray;
    }

    /**
     * 获取从订阅栏目获取热搜词组
     * @date: 2019年6月13日 下午3:11:57
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getHotWordsFromDingyuelanmu($number = 3)
    {
        $list = (new model("guanjiancitongji"))
            ->find("ci")->where("ci<>'' and ci is not null and resou='1' ")
            ->orderBy("paixu asc ,id desc")
            ->all();
        $words = "";
        foreach ($list as $k => $v) {
            if ($words == "") {
                $words = $v['ci'];
            } else {
                $words = $words . "," . $v['ci'];
            }
        }

        $wordsArray = $words == "" ? [] : explode(",", $words);
        $wordsArray = array_unique($wordsArray);
        $temp_wordsArray = [];

        foreach (array_rand($wordsArray, $number) as $k => $v) {
            $temp_wordsArray[] = $wordsArray[$v];
        }
        return $temp_wordsArray;

    }

    /**
     * 查询分类
     * @date: 2019年6月13日 下午3:56:16
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getfenlei()
    {
        $data["sort_id"][] = ["name" => "全部", "value" => ""];
        $data["jibie"][] = ["name" => "全部", "value" => ""];
        $data["bumen"][] = ["name" => "全部", "value" => ""];
        $data["fuchifangxiang"][] = ["name" => "全部", "value" => ""];
        $data["fawenriqi"][] = ["name" => "全部", "value" => ""];

        $parameterM = new parameterModel();
        $sortM = new sortModel();
        $data["sort_id"] = array_merge($data["sort_id"], $sortM->getsortArrayByclassid("3"));
        $data["jibie"] = array_merge($data["jibie"], $parameterM->getparameterArrayByclassid("369"));
        $data["bumen"] = array_merge($data["bumen"], $parameterM->getparameterArrayByclassid("374"));
        $data["fuchifangxiang"] = array_merge($data["fuchifangxiang"], $parameterM->getparameterArrayByclassid("376"));

        //单独处理年份
        $cur_year = date('Y');
        for ($i = 0; $i < 3; $i++) {
            $temp_year = ($cur_year - $i);
            $jiduArray = [];
            $jidunameArray = ["一季度", "二季度", "三季度", "四季度"];
            for ($j = 1, $_j = 0; $j <= 12; $j += 3, $_j++) {
                $temp_mounth_start = $j;
                $temp_mounth_end = $j + 2;
                $jiduArray[] = ["name" => $jidunameArray[$_j], "value" => "{$temp_year}-{$temp_mounth_start}-1|{$temp_year}-{$temp_mounth_end}-31"];
                //echo "{$temp_year}-{$temp_mounth_start}-1|{$temp_year}-{$temp_mounth_end}-31";flush();
            }
            //var_dump($jiduArray);die();
            $data["fawenriqi"][] = ["name" => $cur_year - $i, "value" => "{$temp_year}-1-1|{$temp_year}-12-31", "child" => $jiduArray];


        }
        //单独处理级别===>区
        foreach ($data["jibie"] as $k => $v) {
            if ($v["value"] == "4") {
                $v["child"][] = ["name" => "全部", "value" => $parameterM->getparameterChildIdsByclassid($v["id"], "u2")];
                $v["child"] = array_merge($v["child"], $parameterM->getparameterArrayByclassid($v["id"]));
                $v["value"] = $parameterM->getparameterChildIdsByclassid($v["id"], "u2");
            }
            $data["jibie"][$k] = $v;
        }
        return $data;

    }

    public function getzhengcekuDetail($id)
    {
        $detail = $this->findOne($id);
        if (count($detail) > 0) {
            //更新人气
            $this->query("update sl_zhengceku set renqi=renqi+1 where id={$id} ");
            //查询附件
            $fujianM = new Model("fujian");
            $fujianList = $fujianM->find("leixing,mingcheng,wenjian")->where("laiyuanbianhao='{$detail["fujian"]}' and zhuangtai='成功' ")->all();
            foreach ($fujianList as $k => $v) {
                $v["wenjian"] = $this->common->getHostDomain() . $v["wenjian"];
                $fujianList[$k] = $v;
            }

            $detail["fawenriqi"] = date("Y-m-d", strtotime($detail["fawenriqi"]));
            $detail["fujianlist"] = $fujianList;
            //替换内容图片和文件路径 neirong
            $detail["content"] = str_replace("/public/upload/", $this->common->getHostDomain() . "/public/upload/", $detail["content"]);
            $detail["laiyuan"] = empty($detail["laiyuan"]) ? $detail["fawenbumen"] : $detail["laiyuan"];
            return $detail;
        } else {
            return [];
        }
    }

    /**
     * 查询模块化数据
     * @date: 2019年6月21日 下午5:34:06
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getzhengcekuMokuaihuaDetail($id)
    {
        $parameterM = new parameterModel();
        $detail = $this->findOne($id);
        if (count($detail) > 0) {
            //更新人气
            $this->query("update sl_zhengceku set renqi = renqi + 1 where id = {$id} ");

            $data["biaoti"] = $detail["biaoti"];
            $data["fawenriqi"] = date("Y-m-d", strtotime($detail["fawenriqi"]));
            $data["laiyuan"] = empty($detail["laiyuan"]) ? $detail["fawenbumen"] : $detail["laiyuan"];
            $data["renqi"] = $detail["renqi"];
            $data["hexinneirong"] = $detail["hexinneirong"] == "" ? "无" : $detail["hexinneirong"];
            $data["fuchitiaojian"] = $detail["fuchitiaojian"] == "" ? $detail["shenbaoduixiang"] : $detail["fuchitiaojian"];
            $data["shenbaocailiao"] = $detail["shenbaocailiao"] == "" ? "无" : $detail["shenbaocailiao"];
            $data["liuchengshenbao"] = $detail["liuchengshenbao"] == "" ? "无" : $detail["liuchengshenbao"];
            $data["lianxifangshi"] = $detail["lianxifangshi"] == "" ? "无" : $detail["lianxifangshi"];
            $data["zhengcemingcheng"] = $detail["zhengcemingcheng"] == "" ? "无" : $detail["zhengcemingcheng"];
            $data["fuchitiaojian"] = $data["fuchitiaojian"] == "" ? "无" : $data["fuchitiaojian"];
            $data["fawenzihao"] = $detail["fawenzihao"];
            $data["fawenbumen"] = $detail["fawenbumen"];

            //截止日期
            $data["u4"] = $detail["jiezhiriqi"];
            $data["biaoqian"] = str_replace(",", " ", $detail["biaoqian"]);
            $data["guanjianzi"] = $data["biaoqian"];
            //自定义级别
            $jibiedata = $parameterM->where("u2='{$detail['jibie']}' and classid in (369,373) ")->one();
            if (count($jibiedata) > 0) {
                if ($jibiedata['classid'] == 373) {
                    $data['jibie'] = "区";
                } else {
                    $data['jibie'] = $jibiedata["u1"];
                }

            }
            //处理部门
            $bumendata = $parameterM->where("u2='{$detail['bumen']}' and classid in (374) ")->one();
            if (count($bumendata) > 0) {
                $data['bumen'] = $bumendata["u1"];
            }

            //详细内容
            $data["content"] = $detail["content"];
            $data["dtime"] = $detail["dtime"];

            return $data;
        } else {
            return [];
        }

    }

    /**
     * 单条政策数据格式
     * @date: 2019年6月16日 上午3:57:33
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getonelistByid($id)
    {
        $parameterM = new parameterModel();

        $data = $this->find("id,biaoti,description,biaoqian,fawenriqi,jibie,jiezhiriqi,sort_id")->findOne($id);
        if ($data) {
            //处理发文日期
            $v = $data;
            if ($v['fawenriqi'] != "") {
                $v['fawenriqi'] = date("Y-m-d", strtotime($v['fawenriqi']));
            }

            //处理标题
            $v["biaoti"] = DeleteHtml(html_entity_decode($v["biaoti"]));
            //处理标签
            $v['biaoqian'] = ($v['biaoqian'] == null || $v['biaoqian'] == "") ? [] : explode(",", $v['biaoqian']);
            $v['biaoqian'] = array_slice(Arrayremove_nullvalue($v['biaoqian']), 0, 4);
            //处理申请状态
            if ($v['jiezhiriqi'] == "" || $v['jiezhiriqi'] == null) {
                $v['zhuangtai'] = "";
            } else {
                $zero1 = time();
                $zero2 = strtotime($v['jiezhiriqi']);
                //政策文件
                if ($v["sort_id"] == "6") {
                    if ($zero1 < $zero2) {
                        //echo “zero1早于zero2′;
                        $v['zhuangtai'] = "";
                    } else {

                        $v['zhuangtai'] = "已失效";
                    }
                }

                //资格资质
                if ($v["sort_id"] == "5") {
                    if ($zero1 < $zero2) {
                        //echo “zero1早于zero2′;
                        $v['zhuangtai'] = "申报中";
                    } else {

                        $v['zhuangtai'] = "已截止";
                    }
                }

                //资金扶持
                if ($v["sort_id"] == "4") {
                    if ($zero1 < $zero2) {
                        //echo “zero1早于zero2′;
                        $v['zhuangtai'] = "申报中";
                    } else {

                        $v['zhuangtai'] = "已截止";
                    }
                }


            }

            //自定义标题
            $jibiedata = $parameterM->where("u2={$v['jibie']} and classid in (369,373) ")->one();
            if (count($jibiedata) > 0) {
                if ($jibiedata['classid'] == 373) {
                    $v['biaoti'] = "【区】" . $v['biaoti'];
                } else {
                    $v['biaoti'] = "【{$jibiedata["u1"]}】" . $v['biaoti'];
                }

            }
            return $v;
        } else {
            return [];
        }
    }

    /**
     * 查询列表By IDs
     * @date: 2019年6月19日 下午5:47:26
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getlistByids($ids)
    {
        $idArray = explode(',', $ids);
        $list = [];
        foreach ($idArray as $k => $v) {
            $list[] = $this->getonelistByid($v);

        }
        return $list;
    }

    /**
     * 查询相关政策
     * @date: 2019年6月21日 下午5:38:59
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getRelationListByid($id)
    {
        $detail = $this->getonelistByid($id);
        $biaoqianArray = $detail["biaoqian"];
        $whereStr = "";
        foreach ($biaoqianArray as $k => $v) {
            if ($whereStr == "") {
                $whereStr = "biaoqian like '%{$v}%' ";
            } else {
                $whereStr = $whereStr . " or biaoqian like '%{$v}%' ";
            }
        }
        //根据政策的分类查询政策库列表
        $list["zijinfuchi"] = $this->findBySql("SELECT zc.id,biaoti,DATE_FORMAT(fawenriqi,'%Y-%m-%d') as fawenriqi ,u2 as jibie  from sl_zhengceku as zc,sl_parameter as p where   p.u2=zc.jibie and  (classid= 369 or classid=373  )    and   chaifenzhuangtai=3 and sort_id=4 and ({$whereStr}) and zc.id<>{$id} limit 0,2");
        $list["zigezizhi"] = $this->findBySql("SELECT zc.id,biaoti,DATE_FORMAT(fawenriqi,'%Y-%m-%d') as fawenriqi ,u2 as jibie  from sl_zhengceku as zc,sl_parameter as p where   p.u2=zc.jibie and  (classid= 369 or classid=373  )    and   chaifenzhuangtai=3 and sort_id=5 and ({$whereStr})  and zc.id<>{$id}  limit 0,2");
        $list["zhengcewenjian"] = $this->findBySql("SELECT zc.id,biaoti,DATE_FORMAT(fawenriqi,'%Y-%m-%d') as fawenriqi ,u2 as jibie  from sl_zhengceku as zc,sl_parameter as p where   p.u2=zc.jibie and  (classid= 369 or classid=373  )    and   chaifenzhuangtai=3 and sort_id=6 and ({$whereStr})  and zc.id<>{$id}  limit 0,2");

        //处理级别
        $parameterM = new parameterModel();
        foreach ($list["zijinfuchi"] as $k => &$v) {
            $jibiedata = $parameterM->where("u2 = {$v['jibie']} and classid in (369,373) ")->one();
            if (count($jibiedata) > 0) {
                if ($jibiedata['classid'] == 373) {
                    $v['jibie'] = "区";
                } else {
                    $v['jibie'] = $jibiedata["u1"];
                }
            }
        }
        foreach ($list["zigezizhi"] as $k => &$v) {
            $jibiedata = $parameterM->where("u2 = {$v['jibie']} and classid in (369,373) ")->one();
            if (count($jibiedata) > 0) {
                if ($jibiedata['classid'] == 373) {
                    $v['jibie'] = "区";
                } else {
                    $v['jibie'] = $jibiedata["u1"];
                }
            }
        }
        foreach ($list["zhengcewenjian"] as $k => &$v) {
            $jibiedata = $parameterM->where("u2 = {$v['jibie']} and classid in (369,373) ")->one();
            if (count($jibiedata) > 0) {
                if ($jibiedata['classid'] == 373) {
                    $v['jibie'] = "区";
                } else {
                    $v['jibie'] = $jibiedata["u1"];
                }
            }
        }
        return $list;
    }

    /**
     * 分析关键词和权重
     * @date: 2019年6月20日 下午3:28:11
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getkeywordsByid($id)
    {
        $data = $this->find("id,content")->findOne($id);
        if (!empty($data)) {
            $data["content"] = strip_tags(htmlspecialchars_decode($data["content"]));
            $data["content"] = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", " ", $data["content"]);
        }
        $top_k = 200;
        $content = $data["content"];
        //提取标签=》关键词
        jieba::loadUserDict(__DIR__ . '/../vendor/fukuball/jieba-php/src/dict/user_dict.txt');//导入自定义的词语
        $tags = JiebaAnalyse::extractTags($content, $top_k);

        //计算权重
        $re_word_list = [];
        foreach ($tags as $word => $weight) {
            $_data["ci"] = $word;
            $_data["quanzhong"] = $weight;
            $re_word_list[] = $_data;
        }

        //排序
        $re_word_list = array_orderby($re_word_list, 'quanzhong', SORT_DESC);
        return $re_word_list;
    }

    /**
     * 更新政策库的关键词
     * @date: 2019年6月20日 下午5:16:51
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function updateguanjianciByids($ids = "")
    {
        $whereStr = " 1 = 1 ";
        if ($ids != "") {
            $whereStr = $whereStr . " and id in ({$ids})  ";
        }
        $list = $this->where($whereStr)->all();
        $guanjianciM = new Model("guanjianci");

        //更新用户自定义词典
        $zidianM = new zidianModule();
        $zidianM->UpdateZidian();

        foreach ($list as $k => $v) {
            $id = $v["id"];
            $laiyuanbianhao = $v["guanjianci"];
            //删除原有的关键词
            $guanjianciM->query("delete from sl_guanjianci where laiyuanbianhao='{$laiyuanbianhao}' and  (leixing='系统' or leixing is null) ");
            $biaoqianStr = "";
            //提取关键词
            $word_list = $this->getkeywordsByid($id);
            if ($laiyuanbianhao == "" || $laiyuanbianhao == null) {
                $laiyuanbianhao = $this->common->getOrderId();
            }
            //插入关键词
            foreach ($word_list as $k1 => $v1) {
                //选择前20个关键词
                if ($k1 < 20) {
                    $v1["laiyuanbianhao"] = $laiyuanbianhao;
                    $guanjianciM->insert($v1);
                }

                //组合标签
                if ($k1 < 4) {
                    if ($biaoqianStr == "") {
                        $biaoqianStr = $v1["ci"];
                    } else {
                        $biaoqianStr = $biaoqianStr . "," . $v1["ci"];
                    }
                }
            }
            //更新政策库内容
            $_data["id"] = $id;
            $_data["biaoqian"] = ($v["biaoqian"] == "" || $v["biaoqian"] == null) ? $biaoqianStr : $v["biaoqian"];
            $_data["guanjianci"] = $laiyuanbianhao;
            $this->update($_data);
        }
    }

    /**
     * 更新分类
     * @date: 2019年6月21日 上午10:59:25
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function updateSortidByids($ids)
    {
        $whereStr = "status = 1 and chaifenzhuangtai = 3";
        if ($ids != "") {
            if ($whereStr == "") {
                $whereStr = "   id in ({$ids})  ";
            } else {
                $whereStr = $whereStr . " and id in ({$ids})  ";
            }
        }
        $list = $this->find("id,biaoti,content")->where($whereStr)->all();
        foreach ($list as $k => $v) {
            $status = true;
            $_data["id"] = $v["id"];
            $_data["sort_id"] = "";// 4	   ├─ 资金扶持	5	   ├─ 资格资质	6	   └─ 政策文件
            $pregArray4 = [
                '/((关于).*?(资金项目申报|资助申报|奖励申报)(的通知))/',
                '/资金申报/',
                '/补贴/',
                '/资助/',
                '/奖励资金/',
            ];

            foreach ($pregArray4 as $v1) {
                $preg = $v1;
                preg_match_all($preg, $v["biaoti"], $res);
                if (isset($res[0][0])) {
                    $_data["sort_id"] = '4';
                    $this->update($_data);
                    $status = false;
                    continue;
                }
            }

            //如果已经处理则直接跳过
            if (!$status) {
                continue;
            }

            //匹配资格资质
//             标题/内容为：资质资格申报
//             标题内容中涉及到： 申报 认定申报 中心申报 企业申报 目录申报 计划申报 评价 遴选 险种申报 试点示范

            $pregArray5 = [
                '/申报/',
                '/认定申报/',
                '/中心申报/',
                '/企业申报/',
                '/目录申报/',
                '/计划申报/',
                '/评价/',
                '/遴选/',
                '/险种申报/',
                '/试点示范/',
            ];
            //匹配标题
            preg_match_all('/资质资格申报/', $v["content"], $res5);
            if (isset($res5[0][0])) {
                $_data["sort_id"] = '5';
                $this->update($_data);
                $status = false;
                continue;
            }

            preg_match_all('/申报指南/', $v["content"], $res5);
            if (isset($res5[0][0])) {
                $_data["sort_id"] = '5';
                $this->update($_data);
                $status = false;
                continue;
            }

            //匹配内容
            foreach ($pregArray5 as $v1) {
                $preg = $v1;
                preg_match_all($preg, $v["content"], $res);
                if (isset($res[0][0])) {
                    // var_dump($res);
                    $_data["sort_id"] = '5';
                    //var_dump($_data);
                    $this->update($_data);
                    continue;
                }
            }

            //如果已经处理则直接跳过
            if (!$status) {
                continue;
            }

            //匹配政策文件
            //标题中含有：政策 意见 办法 实施细则 管理办法 计划 措施 若干政策 成都……条
            //关于（印发）……的通知
            $pregArray6 = [
                '/((成都).*?(条))/',
                '/意见/',
                '/政策/',
                '/办法/',
                '/实施细则/',
                '/管理办法/',
                '/计划/',
                '/措施/',
                '/若干政策/',
                '/((印发).*?(的通知))/',

            ];

            foreach ($pregArray6 as $v1) {
                $preg = $v1;
                preg_match_all($preg, $v["biaoti"], $res);
                if (isset($res[0][0])) {
                    $_data["sort_id"] = '6';
                    $this->update($_data);
                    $status = false;
                    continue;
                }
            }
        }
    }

    /**
     * 模块化政策文档
     * @date: 2019年6月21日 下午3:27:06
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function updateMokuaihuaByids($ids)
    {
        $whereStr = " status = 1 and chaifenzhuangtai = 1 ";
        if ($ids != "") {
            if ($whereStr == "") {
                $whereStr = "   id in ({$ids})  ";
            } else {
                $whereStr = $whereStr . " and id in ({$ids})  ";
            }
        }
        $list = $this->find("id,biaoti,content")->where($whereStr)->all();
        //没有内容则不处理
        if (!$list) {
            return;
        }

        $mokuaihuaguizeM = new Model("mokuaihuaguize");
        $mokuaihuaguizeList = $mokuaihuaguizeM->find("fuchitiaojian as shenbaoduixiang ,shenbaocailiao,shenbaoliucheng,lianxifangshi")->all();

        $preg = [];
        //组合分割词
        foreach ($mokuaihuaguizeList as $k => $v) {
            $_pregItem = [];
            foreach ($v as $k1 => $v1) {
                $_preg = "";
                if ($v1 != "") {
                    $_pregArray = explode("|", $v1);
                    if (count($_pregArray) == 0) {
                        $_preg = $v1 . "(.*)";
                    } else {
                        $_preg = $_pregArray[0] . "(.*)" . $_pregArray[1];
                    }
                    $_preg = "/({$_preg})/";
                    $_pregItem[$k1] = $_preg;
                }

            }
            $preg[] = $_pregItem;

        }

        foreach ($list as $k => $v) {
            $content = html_entity_decode($v["content"]);

            //循环匹配
            foreach ($preg as $v1) {
                $cur_pipei_num = 0;//默认匹配出的模块数量
                //匹配具体的每一个字段
                foreach ($v1 as $k11 => $v11) {
                    preg_match_all($v11, $content, $res);
                    if (isset($res[0][0])) {
                        //var_dump($res);
                        $_data[$k11] = $res[2][0];
                    }
                }

                //删除可能为空的数据
                foreach ($_data as $k11 => $k11) {
                    if ($v11 == '') {
                        unset($_data[$k11]);
                    }
                }

                if (isset($_data) && count($_data) > 0) {
                    //当前规则匹配出的结果数更过，则更新
                    $_data["id"] = $v["id"];
                    $_data["chaifenzhuangtai"] = "2";
                    $this->update($_data);
                }
            }
        }
    }

    /**
     * 查询政策库每条记录的关键词模型
     * @date: 2019年6月24日 上午11:34:51
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getguanjianciArrayByids($ids = "")
    {
        $whereStr = " status =1 and chaifenzhuangtai = 3 "; //暂时关闭状态条件

        if ($ids != "") {
            $whereStr = $whereStr . " and id in ({$ids}) ";
        }
        $list = $this->find("id,biaoti,guanjianci,zuigaojine")->where($whereStr)->all();
        //查询关键词列表
        $guanjianciM = new Model("guanjianci");
        foreach ($list as $k => $v) {
            $laiyuanbianhao = $v["guanjianci"];
            $_guanjianciArray = $guanjianciM->find("ci,quanzhong")->where("laiyuanbianhao ='{$laiyuanbianhao}' ")->all();
            $v["guanjianci"] = [];
            foreach ($_guanjianciArray as $k1 => $v1) {
                $v["guanjianci"][$v1["ci"]] = $v1["quanzhong"];
            }
            $list[$k] = $v;
        }
        return $list;
    }

    /**
     * 设置缓存政策列表
     * @date: 2019年8月12日 下午4:36:43
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function setredislist($ids = "")
    {
        $list = $this->getguanjianciArrayByids($ids);
        //实例化redis
        $redis = new Redis();
        //连接
        $redis->connect('127.0.0.1', 6379);
        //检测是否连接成功
        $redis->set('zhengcekuguanjiancilist', json_encode($list, true));
        //设置键的过期时间
        $expireTime = mktime(23, 59, 59, date("m"), date("d"), date("Y"));
        $redis->expireAt('zhengcekuguanjiancilist', $expireTime);
    }

    /**
     * 获取缓存政策列表
     * @date: 2019年8月12日 下午4:36:43
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function getredislist($ids = "")
    {
        //实例化redis
        $redis = new Redis();
        //连接
        $redis->connect('127.0.0.1', 6379);
        //检测是否连接成功
        if (!$redis->get('zhengcekuguanjiancilist')) {
            $this->setredislist($ids = "");
        }
        $list = json_decode($redis->get('zhengcekuguanjiancilist'), true);
        return $list;
    }

    /**
     * 插入四方平台的数据
     * @date: 2019年9月2日 下午4:11:01
     * @param
     * @return :
     * @author : 龚华尧
     */
    public function insertFromSifangdata($data)
    {
        if (!empty($data)) {
            // 数据不存在则插入
            $_itemdata = $this->where("biaoti='{$data["biaoti"]}' ")->one();
            if (count($_itemdata) == 0) {
                foreach ($data as $k => $v) {
                    if ($v == "") {
                        unset($data[$k]);
                    }
                }
                $_id = $this->insert($data);
                return $_id;
            }
        }
        return '';
    }

    /**
     * 函数用途描述
     * @date: 2019年6月28日 上午4:28:50
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function TreatmentSifangshujuByids($ids = "")
    {
        $whereStr = " status = 1 and chaifenzhuangtai = 4 "; //暂时关闭状态条件
        if ($ids != "") {
            $whereStr = $whereStr . " and id in ({$ids}) ";
        }
        $list = $this->find("*")->where($whereStr)->orderBy("id desc")->all();

        $paremetarM = new parameterModel();
        $fujianM = new Model("fujian");
        foreach ($list as $k => $v) {
            //如果已存在则不删除重复数据
            $_data = $this->where("biaoti='{$v["biaoti"]}' and id <>'{$v["id"]}' ")->orderBy("id desc")->one();
            if (count($_data) > 0) {
                $this->delete($_data["id"]);
                continue;
            }

            //处理分裂 资金扶持，政策文件等
            $_zijinfuchiClassidList = [174, 175, 176];//资金扶持
            $_zigezizhiClassidList = [177, 178, 179];//资格资质
            $_zhengcewenjianClassidList = [172, 173];//政策文件
            if (in_array($v["sifangfenlei"], $_zijinfuchiClassidList)) {
                $v["sifangfenlei"] = 4;
            } else if (in_array($v["sifangfenlei"], $_zigezizhiClassidList)) {
                $v["sifangfenlei"] = 5;
            } else if (in_array($v["sifangfenlei"], $_zhengcewenjianClassidList)) {
                $v["sifangfenlei"] = 6;
            } else {
                $v["sifangfenlei"] = 0;
            }

            $v["sort_id"] = $v["sifangfenlei"];
            //处理摘要
            $v["description"] = DeleteHtml(html_entity_decode($v["description"]));
            //处理最高金额
            $v["zuigaojine"] = 0;
            //处理标签
            $v["biaoqian"] = str_replace(" ", ",", $v["biaoqian"]);
            //处理详情 包含等文件，图片等
            //处理附件
            $v["fujian"] = $this->common->getOrderId();
            $fujianList = $this->common->getLinkandHtml(html_entity_decode($v["content"]));
            foreach ($fujianList as $k1 => $v1) {
                $extArray = ["doc", "docx", "xls", "xlsx", "ppt", "pdf", "rar", "zip"];
                if (in_array($this->common->getExt($v1), $extArray)) {
                    //开始下载
                    $downloaddata = $this->common->download_fileToServer("http://www.cdsme.com" . $v1, "public/download", $v["fujian"] . "." . $this->common->getExt($v1), 1);
                    //写入附件表
                    $fujiandata["laiyuanbianhao"] = $v["fujian"];
                    $fujiandata["wenjian"] = "/" . $downloaddata["save_path"];
                    $fujiandata["zhuangtai"] = $downloaddata["save_path"] != "" ? "成功" : "失败";
                    $fujiandata["leixing"] = $this->common->getExt($v1);
                    $fujiandata["mingcheng"] = DeleteHtml(html_entity_decode($k1));
                    $fujianM->insert($fujiandata);
                }
            }
            unset($v["content"]);
            unset($v["hexinneirong"]);
            unset($v["fuchitiaojian"]);
            unset($v["shenbaocailiao"]);
            unset($v["liuchengshenbao"]);
            unset($v["lianxifangshi"]);
            unset($v["shenbaoduixiang"]);

            //处理状态
            $v["chaifenzhuangtai"] = 4;//四方平台导入待处理

            //处理级别
            //参数存在则修改
            $jibieParemetarData = $paremetarM->where("u1='{$v["jibie"]}' and classid=369 ")->one();
            if (count($jibieParemetarData) > 0) {
                $v["jibie"] = $jibieParemetarData['u2'];
            } else {
                continue;
            }

            //处理部门
            //参数存在则修改
            $bumenParemetarData = $paremetarM->where("u1='{$v["bumen"]}' and classid=374 ")->one();
            if (count($bumenParemetarData) > 0) {
                $v["bumen"] = $bumenParemetarData['u2'];
            } else {
                continue;
            }
            $this->update($v);
        }
    }

}